package thread;

public class ProducerAndConsumer {

	ManTou[] arrMT = new ManTou[10];
	int i = 0;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ProducerAndConsumer pac = new ProducerAndConsumer();
		Producer p = new Producer(pac, 30);
		Consumer c = new Consumer(pac, 30);
		Thread tp = new Thread(p);
		Thread tc = new Thread(c);
		tp.start();
		tc.start();
	}

	public synchronized void produce(String number) {
		while (arrMT.length == i) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		ManTou mt = new ManTou(number);
		System.out.println("**********生产馒头：" + number + "**********");
		arrMT[i] = mt;
		i++;
	}

	public synchronized void consum() {
		while (i == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		i--;
		System.out.println("**********吃馒头：" + arrMT[i].getNumber()
				+ "**********");
	}
}

class Producer implements Runnable {

	int i;

	ProducerAndConsumer pac;

	Producer(ProducerAndConsumer pac, int i) {
		this.i = i;
		this.pac = pac;
	}

	public void run() {
		for (int n = 0; n < i; n++) {
			pac.produce(String.valueOf(n));
			try {
				Thread.currentThread().sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

class Consumer implements Runnable {

	int i;

	ProducerAndConsumer pac;

	Consumer(ProducerAndConsumer pac, int i) {
		this.i = i;
		this.pac = pac;
	}

	public void run() {
		for (int n = 0; n < i; n++) {
			pac.consum();
			try {
				Thread.currentThread().sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

class ManTou {

	String number;

	ManTou(String number) {
		this.number = number;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}
}